﻿
var scaledValuePatt = /^scaled-\d+$/;
var refSizes = [320, 480, 800, 1000, 1500];


function RwdImagesResizing() {
    var refWidth = $(window).width();
    $(window.scaledImages).each(function () {
        var w = refWidth * $(this).data('scaled') / 100;
        w = FindRwdWidth(w);

        var $img = $(this);
        var url = $img.data('oryginal-src').replace('320', w);
        LoadImage($img, url);
    });
}

function LoadImage($img, url) {
    if (window.XMLHttpRequest) {
        var rAr = $img.data('rar');
        if (!rAr) {
            rAr = new Array();
            $img.data('rar', rAr);
        }
        else {
            for (var u in rAr) {
                if (rAr[u])
                    rAr[u].abort();
            }
        }
        rAr[url] = req;
        var req = new XMLHttpRequest();
        req.open('GET', url, true);
        req.onload = function (e) {
            delete rAr[url];
            $img.attr('src', url);
        };
        req.send(null);
    } else {
        $('<img style="display:none" />').appendTo($('body')).load(function () {
            $img.attr('src', url);
        }).attr('src', url);
    }
}

function FindRwdWidth(w) {
    var sw = refSizes[refSizes.length - 1];
    for (var xw = 0; xw < refSizes.length; xw++) {
        if (refSizes[xw] >= w)
            return refSizes[xw];
    }
    return refSizes[refSizes.length - 1];
}

$(function () {
    window.scaledImages = $('img.scaled-image').toArray();
    $(window.scaledImages).each(function () {
        var scaled = 100;
        $($(this).attr('class').split(' ')).each(function () {
            if (scaledValuePatt.test(this.toString())) {
                scaled = parseInt(this.toString().replace('scaled-', ''));
                return false; // przerywa
            }
        });
        $(this).data('oryginal-src', $(this).attr('src')).data('scaled', scaled);
    });
    RwdImagesResizing();
    $(window).resize(function () {
        RwdImagesResizing();
    });
});
